package com.example.haojiutao.controller.user;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.example.haojiutao.common.Result;
import com.example.haojiutao.config.AliReturnPay;
import com.example.haojiutao.config.AlipayConfig;
import com.example.haojiutao.model.domain.Goods;
import com.example.haojiutao.model.domain.Order;
import com.example.haojiutao.model.domain.User;
import com.example.haojiutao.model.vo.response.CommentOrderDetailVO;
import com.example.haojiutao.model.vo.response.OrderGoodsDetailVO;
import com.example.haojiutao.service.GoodsService;
import com.example.haojiutao.service.OrderService;
import com.example.haojiutao.utils.H5LoginUserUtil;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Description: 订单控制层
 * @Author: zhou_yuan
 * @CreateTime： 2024/1/22 14:20
 */
@Slf4j
@RestController
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private AlipayConfig alipayConfig;
    /*
     * @Description: 用户下单，通过在商品详情页下单，买卖填写地址、电话等信息，提交订单
     * @Author: zhou_yuan
     * @CreateTime： 2024/1/22 14:30
     * @param: order
     * @return: com.example.haojiutao.common.Result
     */
    @PostMapping("/user/order/{goodsId}")
    public Result insertOrder(@RequestBody@PathVariable Integer goodsId) {
        Order order = new Order();
        Goods goods = goodsService.selectById(goodsId);
        order.setGoodsId(goodsId);
        order.setGoodsName(goods.getGoodsName());
        order.setSellerName(goods.getSellerName());
        order.setUserName("fourth");
        order.setOrderPrice(order.getAmount() * goods.getPrice());
        System.out.println("=======================" + order.getAmount());
        log.info("新增订单；{}", order);
        System.out.println("___________________" + order.getOrderNumber());
        return orderService.insertOrder(order);
    }

    /*
     * @Description: 确认收货接口,买家收货后点击签收按钮，后台修改订单状态为“已签收”
     * @Author: zhou_yuan
     * @CreateTime： 2024/1/22 14:34
     * @param: order
     * @return: com.example.haojiutao.common.Result
     */
    @PutMapping("/user/order/orderstatus/{orderNumber}")
    public Result updateOrder(@PathVariable Integer orderNumber) {
        Order order = new Order();
        log.info("更改收货状态");
        order.setOrderNumber(orderNumber);
        return orderService.updateOrder(order);
    }
    /*
     * @Description:卖家添加物流单号，更改订单状态为待收货
     * @Author: zhou_yuan
     * @CreateTime： 2024/1/22 14:37
     * @param: order
     * @return: com.example.haojiutao.common.Result
     */
    @PutMapping("/user/order/Tracking/{orderNumber}")
    public Result updateOrderLogistics(@RequestBody Integer orderNumber) {
        Order order = new Order();
        log.info("卖家添加物流信息");
        order.setOrderNumber(orderNumber);
        System.out.println("==============" + order.getTrackingNumber());
        return orderService.updateOrderLogistics(order);
    }

    /*
     * @Description:查看订单
     * @Author: zhou_yuan
     * @CreateTime： 2024/1/22 14:39
     * @param: orderNumber
     * @return: com.example.haojiutao.common.Result
     */
    @GetMapping("/user/order/ordernumber/{orderNumber}")
    public Result selectByOrderNumber(@PathVariable Integer orderNumber) {
        log.info("查看订单");
        OrderGoodsDetailVO order = orderService.selectByOrderNumber(orderNumber);

        return Result.success("查询成功", order);
    }

    /*
     * @Description: 显示个人订单列表 TODO根据用户名
     * @Author: zhou_yuan
     * @CreateTime： 2024/1/22 14:57
     * @param: goods
     * @return: com.example.haojiutao.common.Result
     */
    @GetMapping("/user/order/{userName}")
    public Result selectList(@PathVariable String userName) {
        OrderGoodsDetailVO orderGoodsDetailVO = new OrderGoodsDetailVO();
        orderGoodsDetailVO.setUserName(userName);
        List<OrderGoodsDetailVO> order1 = orderService.selectListByUser(orderGoodsDetailVO);
        PageInfo<OrderGoodsDetailVO> pageInfo = new PageInfo<>(order1);
        return Result.success("查询成功", pageInfo);
    }
    /*
     * @Description: 显示待发货列表
     * @Author: zhou_yuan
     * @CreateTime： 2024/1/22 15:06
     * @param: goods
     * @return: com.example.haojiutao.common.Result
     */
    @GetMapping("/user/order/backorder/{userName}")
    public Result selectBackOrder(@PathVariable String userName) {
        OrderGoodsDetailVO orderGoodsDetailVO = new OrderGoodsDetailVO();
        orderGoodsDetailVO.setUserName(userName);
        List<OrderGoodsDetailVO> order1 = orderService.selectBackOrder(orderGoodsDetailVO);
        PageInfo<OrderGoodsDetailVO> pageInfo = new PageInfo<>(order1);
        return Result.success("查询成功", pageInfo);
    }
    /*
     * @Description: 待收货订单列表
     * @Author: zhou_yuan
     * @CreateTime： 2024/1/22 15:09
     * @param: goods
     * @return: com.example.hoajiutao.common.Result
     *
     */
    @GetMapping("/user/order/aftersend/{userName}")
    public Result selectAfterSendOrder(@PathVariable String userName) {
        OrderGoodsDetailVO orderGoodsDetailVO = new OrderGoodsDetailVO();
        orderGoodsDetailVO.setUserName(userName);
        List<OrderGoodsDetailVO> order1 = orderService.selectAfterSendOrder(orderGoodsDetailVO);
        PageInfo<OrderGoodsDetailVO> pageInfo = new PageInfo<>(order1);
        System.out.println("!!!!!!!" + orderGoodsDetailVO);
        System.out.println("!!!!!!!" + order1);
        return Result.success("查询成功", pageInfo);
    }

    /*
     * @Description: 待付款订单列表
     * @Author: zhou_yuan
     * @CreateTime： 2024/1/22 15:18
     * @param: goods
     * @return: com.example.hoajiutao.common.Result
     */

    //    @RequestMapping("/user/order/beforepay/{userName}")
    @GetMapping("/user/order/beforepay/{userName}")
    public Result selectBeforePayOrder(@PathVariable String userName) {
        User loginUser = H5LoginUserUtil.getLoginUser();
        System.out.println(loginUser.getId());
        OrderGoodsDetailVO orderGoodsDetailVO = new OrderGoodsDetailVO();
        orderGoodsDetailVO.setUserName(userName);
        List<OrderGoodsDetailVO> order1 = orderService.selectBeforePayOrder(orderGoodsDetailVO);
        PageInfo<OrderGoodsDetailVO> pageInfo = new PageInfo<>(order1);
        System.out.println("!!!!!!!" + orderGoodsDetailVO);
        System.out.println("!!!!!!!" + order1);
        return Result.success("查询成功", pageInfo);
    }
    /**
     * @Description: 我的订单列表接口，根据orderState查询不同状态的订单列表
     * @Author: cheng_jianzhen
     * @CreateTime: 2024/3/21 15:08
     * @param: order
     * @return: com.example.haojiutao.common.Result
     **/
    @GetMapping("/user/order")
    public Result selectListByUser(Order order) {
        List<Order> orderList = orderService.selectList(order);
        PageInfo<Order> pageInfo = new PageInfo<>(orderList);
        return Result.success("查询成功！", pageInfo);
    }


    /*
     * @Description: 调用支付宝接口进行支付，跳转到支付宝页面
     * @Author: zhou_yuan
     * @CreateTime： 2024/2/4 14:47
     * @param: order
     * @param: response
     */
    @CrossOrigin(origins={"http://localhost:5173"}, allowCredentials = "true")
    @GetMapping("/user/order/pay/{orderNumber}")
    public void payOrder(@PathVariable Integer orderNumber, HttpServletResponse response) {
        Order order1 = orderService.selectById(orderNumber);
        String s = String.valueOf(order1.getOrderNumber());
        Double orderPrice = order1.getOrderPrice();
        try {
            //1.创建client，通过阿里SDK提供的client，负责调用支付宝的API
            AlipayClient alipayClient = new DefaultAlipayClient(
                    alipayConfig.getServerUrl(),
                    alipayConfig.getAppId(),
                    alipayConfig.getAppPrivateKey(),
                    alipayConfig.getFormat(),
                    alipayConfig.getCharset(),
                    alipayConfig.getAlipayPublicKey(),
                    alipayConfig.getSignType()
            );
            //2.创建request，并设置request参数
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            request.setNotifyUrl(alipayConfig.getNotifyUrl());//设置异步地址
//            request.setReturnUrl("");//设置支付成功后的跳转地址
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("out_trade_no", s);// 商户订单号
            jsonObject.put("total_amount", orderPrice);// 商品价格
            jsonObject.put("subject", order1.getGoodsName());// 商品标题
            jsonObject.put("product_code", "FAST_INSTANT_TRADE_PAY");
            request.setBizContent(jsonObject.toString());
            //判断是否执行成功，即是否支付成功

//            AlipayTradePagePayResponse execute = alipayClient.pageExecute(request);
//            boolean success = execute.isSuccess();
//            if(success){
//                System.out.println("调用成功");
//                Result result = orderService.updateOrder1(order1);
//            }else {
//                System.out.println("调用失败");
//            }
            //执行请求，拿到响应的结果，返回给浏览器
            String form = "";
            form = alipayClient.pageExecute(request).getBody();
            //设置响应结果，将返回的内容写出到浏览器
            response.setContentType("text/html;charset=" + alipayConfig.getCharset());
            response.getWriter().write(form);//直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        order1.setOrderState("待发货");
    }

    /*
     * @Description: 设置支付宝同步返回支付结果url，可以以此结果做后续业务逻辑处理 可为空
     * @Author: zhou_yuan
     * @CreateTime： 2024/2/4 15:24
     * @param: request
     * @param: response
     * @param: aliReturnPay
     */
    @PostMapping("/user/order/call")
    public void call(HttpServletRequest request, HttpServletResponse response, AliReturnPay aliReturnPay) {
        response.setContentType("type=text/html;charset=UTF-8");
        System.out.println("当前订单编号：" + aliReturnPay.getOut_trade_no() + "当前订单的状态" + aliReturnPay.getTrade_status());
    }

    /*
     * @Description: 支付宝回调方法，获取一个订单是否成功支付
     * @Author: zhou_yuan
     * @CreateTime： 2024/2/4 15:27
     * @param: order
     * @return: java.lang.String
     */
    @GetMapping("/order/isSuccess")
    public Result isSuccess(Order order){

        Order order1 = orderService.selectById(order.getOrderNumber());
        String s = String.valueOf(order1.getOrderNumber());
//        order1.setOrderState("待发货");
        try {
            //1.创建client，通过阿里SDK提供的client，负责调用支付宝的API
            AlipayClient alipayClient = new DefaultAlipayClient(
                    alipayConfig.getServerUrl(),
                    alipayConfig.getAppId(),
                    alipayConfig.getAppPrivateKey(),
                    alipayConfig.getFormat(),
                    alipayConfig.getCharset(),
                    alipayConfig.getAlipayPublicKey(),
                    alipayConfig.getSignType()
            );
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("out_trade_no", s);// 商户订单号
//            jsonObject.put("trade_no",aliPay.getTotalAmount());//支付宝订单编号
//            jsonObject.put("query_options",trade_settle_info);//指定需要返回那些信息
            request.setBizContent(jsonObject.toString());
            AlipayTradeQueryResponse response = alipayClient.execute(request);

            if(response.isSuccess()){
//                System.out.println("调用成功");
                order1.setOrderState("待发货");
//                System.out.println(response.getBody());
            }else {
                System.out.println("调用失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


//    public void refund(HttpServletResponse response,HttpSession session){
//        response.setContentType("text/html;charset=utf-8");
//        PrintWriter out = response.getWriter();
//        //获得初始化的AlipayClient
//        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
//        //设置请求参数
//        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
//        //商户订单号，必填
//        String out_trade_no = new String(订单号);
//        //需要退款的金额，该金额不能大于订单金额，必填
//        String refund_amount = new String(退款金额);
//        //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
//        String out_request_no = new String(UUID.randomUUID().toString());
//
//        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
//                + "\"refund_amount\":\""+ refund_amount +"\","
//                + "\"out_request_no\":\""+ out_request_no +"\"}");
//        //请求
//        String result = alipayClient.execute(alipayRequest).getBody();
//        //输出
//        out.println(result);以下写自己的订单退款代码
//    }

    /*
     * @Description: 取消订单，当买家未付款或未成功付款时，实现：使用时间戳，当时间流逝完时执行取消订单
     *
     * @Author: zhou_yuan
     * @CreateTime： 2024/2/5 17:24
     * @param: orderNumber
     * @return: com.example.haojiutao.common.Result
     **/
    @DeleteMapping("/user/order/{orderNumber}")
    public Result delete1(@PathVariable("orderNumber") Integer orderNumber) {

        return orderService.deleteById(orderNumber);
    }

    @PutMapping("/user/order/comment/{orderNumber}")
    public Result updateOrderComment(@PathVariable Integer orderNumber) {

        return orderService.updateOrderComment(orderNumber);
    }


}
